<?php

namespace Admin\Controller;

use Core\Controller\AdminBaseController;
use Core\Exception\BusinessException;
use Core\Session\AdminSessionHelper;
use Exception;
use Zend\Json\Json;
use Zend\View\Model\JsonModel;
use Zend\View\Model\ViewModel;

class TemplateController extends AdminBaseController {

    public function indexAction() {

    }

    public function listAction(){
        try{
            $templateTable = $this->getTableFinder()->getTemplateTable(
                AdminSessionHelper::getCurrentLang()
            );
            $allTemplates = $templateTable->fetchAll();
            return new JsonModel(array('rows'=> $allTemplates->toArray(),'success'=>true));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function addAction()
    {
        try{
            return new ViewModel(array('treeData'=>Json::encode($this->getBlockInstanceTreeData())));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    private function getBlockInstanceTreeData(){
        $blockClass = $this->getTableFinder()->getBlockClassTable();

        $resultArr = array();
        $allBlockClass = $blockClass->fetchAll();
        $tmp = 0;
        foreach ($allBlockClass as $blockClassItem) {
            if($tmp == 0)
                $isExpanded = true;
            else
                $isExpanded = false;

            $allBlockInstances = $blockClassItem->getAllBlockInstance();
            $blockInstanceArr = array();
            foreach ($allBlockInstances as $blockInstanceItem) {
                array_push($blockInstanceArr, array('id'=>$blockInstanceItem->id,
                    'text'=>$blockInstanceItem->name
                ));
            }
            array_push($resultArr, array('id'=>$blockClassItem->id,
                'text'=>$blockClassItem->name, 'expanded'=>$isExpanded,
                'items'=>$blockInstanceArr));
            $tmp++;
        }
        return $resultArr;
    }

    public function loadAction(){
        try{
            $viewModel = new ViewModel();
            $viewModel->setTerminal(true);

            $templateFile = $this->params()->fromPost("templateFile");
            $viewModel->setVariable('templateFile', $templateFile);
            $viewModel->setVariable('isAdmin', true);
            $templateId = $this->params()->fromPost("templateId");
            if($templateId){
                $templateTable = $this->getTableFinder()->getTemplateTable(
                    AdminSessionHelper::getCurrentLang()
                );
                $templateItem = $templateTable->getTemplate($templateId);
                $viewModel->setVariable('templateFile', $templateFile);
                $viewModel->setVariable('templateItem', $templateItem);

            }

            return $viewModel;

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    function saveAction(){
        try{

            $id = $this->params()->fromPost('templateId');
            $name = $this->params()->fromPost('name');
            $description = $this->params()->fromPost('description');
            $filePath = $this->params()->fromPost('filePath');
            $imgPath = $this->params()->fromPost('imgPath');
            $blockArr = $this->params()->fromPost('blockArr');
            $data =array("name"=>$name, "description"=>$description, "file_name"=>$filePath,
                "thumb_image"=>$imgPath);

            $templateTable = $this->getTableFinder()->getTemplateTable(
                AdminSessionHelper::getCurrentLang()
            );

            if($id) {
                $template_Item = $templateTable->getTemplate($id);
                $templateTable->update($data, $id);
                //update all block
                $template_Item->removeAllBlock();
                if($blockArr)
                    foreach ($blockArr as $blockItem) {
                        $tmpArr = explode("$$$", $blockItem);
                        $template_Item->addBlock($tmpArr[0], $tmpArr[1]);
                    }
            }  else{
                $id = $templateTable->insert($data);
                $template_Item = $templateTable->getTemplate($id);
                //add all block
                if($blockArr)
                    foreach ($blockArr as $blockItem) {
                        $tmpArr = explode("$$$", $blockItem);
                        $template_Item->addBlock($tmpArr[0], $tmpArr[1]);
                    }
            }
            return new JsonModel(array("success"=>true, "id"=>$id));

        }
        catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function removeAction(){

        try{

            $id = $this->params()->fromPost('id');
            $templateTable = $this->getTableFinder()->getTemplateTable(
                AdminSessionHelper::getCurrentLang()
            );
            $template_Item = $templateTable->getTemplate($id);
            if(!$template_Item){
                throw new BusinessException("Không tìm thấy template phù hợp");
            }
            $allPages =  $template_Item->getAllPages();
            if($allPages->count() > 0)
                throw new BusinessException("Một số trang vẫn đang sử dụng template: ".$template_Item->name.", không thể xóa.");
            $templateTable->delete($id);
            return new JsonModel(array('success'=>true));

        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    function lightUpdateAction(){
        try{
            $id = $this->params()->fromPost('id');
            $name = $this->params()->fromPost('name');
            $description = $this->params()->fromPost('description');
            $filePath = $this->params()->fromPost('file_name');
            if(!$id)
                throw new BusinessException('Bạn chưa chọn template để cập nhật');
            $data =array( "name"=>$name, "description"=>$description, "file_name"=>$filePath);
            $templateTable = $this->getTableFinder()->getTemplateTable(
                AdminSessionHelper::getCurrentLang()
            );
            $templateTable->update($data, $id);

            return new JsonModel(array("success"=>true, "id"=>$id));
        }
        catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }
    }

    public function editAction()
    {
        try{
            $id = $this->params()->fromQuery('id');
            if(!$id) throw new BusinessException("Template id null");
            $templateTable = $this->getTableFinder()->getTemplateTable(
                AdminSessionHelper::getCurrentLang()
            );
            $template = $templateTable->getTemplate($id);
            return new ViewModel(array('templateItem'=>$template,
            'treeData'=>Json::encode($this->getBlockInstanceTreeData())));
        }catch(Exception $e){
            $this->fireExceptionEvent($e, \Core\Constant::$EVENT_NAME_ADMIN_EXCEPTION);
            return $this->genJsonErrorView($e);
        }

    }

    public function editTempAction(){
        $file_path = $this->params()->fromQuery('file_path');
        $this->layout('temp_edit_layout.php');

        return new ViewModel(array('templateFile'=>$file_path));
    }
}